package com.hl.card.common.util;

import java.io.*;
import java.net.*;
import java.util.Map;
import java.util.UUID;

/**
 * 
 */
public class HttpClient {
	CookieManager ca = new CookieManager();
	static String sessionID = "";
	private static String get(String url, String charset, int time) {
		try {
			String key = "";
			String cookieVal = "";

			URL httpURL = new URL(url);
			HttpURLConnection http = (HttpURLConnection) httpURL
					.openConnection();
			http.setConnectTimeout(time);
			http.setReadTimeout(time);
			http.setRequestProperty("accept", "*/*");
			http.setRequestProperty("connection", "Keep-Alive");
			http.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			if (!sessionID.equals("")) {
				http.setRequestProperty("Cookie", sessionID);
			}
			for (int i = 1; (key = http.getHeaderFieldKey(i)) != null; i++) {
				if (key.equalsIgnoreCase("set-cookie")) {
					cookieVal = http.getHeaderField(i);
					cookieVal = cookieVal.substring(
							0,
							cookieVal.indexOf(";") > -1 ? cookieVal
									.indexOf(";") : cookieVal.length() - 1);
					sessionID = sessionID + cookieVal + ";";
				}
			}
			BufferedReader br = new BufferedReader(new InputStreamReader(
					http.getInputStream(), charset));
			StringBuilder sb = new StringBuilder();
			String temp = null;
			while ((temp = br.readLine()) != null) {
				sb.append(temp);
				sb.append("\n");
			}
			br.close();
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String post(String url, String data, String charset, int time) {
		try {
			URL httpURL = new URL(url);
			String key = null;
			String cookieVal = null;
			HttpURLConnection http = (HttpURLConnection) httpURL
					.openConnection();
			http.setConnectTimeout(time);
			http.setReadTimeout(time);

			http.setDoOutput(true);
			http.setDoInput(true);
			if (!sessionID.equals("")) {
				http.setRequestProperty("Cookie", sessionID);
			}
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
					http.getOutputStream(), charset));
			bw.write(data);
			bw.close();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					http.getInputStream(), charset));
			StringBuilder sb = new StringBuilder();
			String temp = null;
			while ((temp = br.readLine()) != null) {
				sb.append(temp);
				sb.append("\n");
			}
			br.close();
			for (int i = 1; (key = http.getHeaderFieldKey(i)) != null; i++) {
				if (key.equalsIgnoreCase("set-cookie")) {
					cookieVal = http.getHeaderField(i);
					cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
					sessionID = sessionID + cookieVal + ";";
				}
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static InputStream httpGetImageByte(String requestUrl){
		try {
			URL url = new URL(requestUrl);
			URLConnection conn =  url.openConnection();
			conn.setUseCaches(false);
			InputStream is = conn.getInputStream();
			return getInputStream(is);
		} catch (ConnectException ce) {
			System.out.println("连接超时：{}");
		} catch (Exception e) {
			System.out.println("https请求异常：{}");
		}
		return null;
	} 
	
	public static InputStream getInputStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        //创建一个Buffer字符串  
        byte[] buffer = new byte[1024];  
        //每次读取的字符串长度，如果为-1，代表全部读取完毕  
        int len = 0;  
        //使用一个输入流从buffer里把数据读取出来  
        while( (len=inStream.read(buffer)) != -1 ){  
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
            outStream.write(buffer, 0, len);  
        }  
        //关闭输入流  
        inStream.close();  
        //把outStream里的数据写入内存  
        return new ByteArrayInputStream(outStream.toByteArray()); 
    }  
	
	public static String httpsRequestImage(String requestUrl, InputStream is){
        String boundary = UUID.randomUUID().toString(); // 边界标识 随机生成
        String prefix = "--", end = "\r\n";
        String content_type = "multipart/form-data"; // 内容类型
        String CHARSET = "utf-8"; // 设置编码
        int TIME_OUT = 10 * 10000000; // 超时时间
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", "utf-8"); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", content_type + ";boundary=" + boundary);
            /**
             * 当文件不为空，把文件包装并且上传
             */
            OutputStream outputSteam = conn.getOutputStream();
            DataOutputStream dos = new DataOutputStream(outputSteam);

            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(prefix);
            stringBuffer.append(boundary);
            stringBuffer.append(end);
            dos.write(stringBuffer.toString().getBytes());

            String name = "userName";
            dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + end);
            dos.writeBytes(end);
            dos.writeBytes("zhangSan");
            dos.writeBytes(end);


                StringBuffer sb = new StringBuffer();
                sb.append(prefix);
                sb.append(boundary);
                sb.append(end);

                /**
                 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 */

                sb.append("Content-Disposition: form-data; name=\"media\"; filename=\"filename.jpg\"" + end);
                sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + end);
                sb.append(end);
                dos.write(sb.toString().getBytes());
                byte[] bytes = new byte[8192];//8k
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);

                }
                is.close();
                dos.write(end.getBytes());//一个文件结束标志

            byte[] end_data = (prefix + boundary + prefix + end).getBytes();//结束 http 流 
            dos.write(end_data);
            dos.flush();
            /**
             * 获取响应码 200=成功 当响应成功，获取响应的流
             */
//            int res = conn.getResponseCode();
         // 从输入流读取返回内容
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			return buffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;

    }

	/**
	 * 将Map存储的对象，转换为key=value&key=value的字符
	 *
	 * @param requestParam
	 * @param coder
	 * @return
	 */
	public static String getRequestParamString(Map<String, String> requestParam, String coder) {
		if (null == coder || "".equals(coder)) {
			coder = "UTF-8";
		}
		StringBuffer sf = new StringBuffer();
		String reqstr = "";
		if (null != requestParam && 0 != requestParam.size()) {
			for (Map.Entry<String, String> en : requestParam.entrySet()) {
				try {
					sf.append(en.getKey()
							+ "="
							+ (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder
							.encode(en.getValue(), coder)) + "&");
				} catch (UnsupportedEncodingException e) {
					return "";
				}
			}
			reqstr = sf.substring(0, sf.length() - 1);
		}
		return reqstr;
	}

	public static String doPost(String url, Map<String, Object> paramMap) {
		return doPost(url, paramMap);
	}
}
